<?php

namespace App\Http\Controllers\Business;


use App\Events\AppointEvent;
use App\Events\Event;
use App\Events\StudentEvent;
use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\System\NoticeConfig;
use App\Model\System\SystemConfig;
use App\Model\System\User;
use Illuminate\Http\Request;
use App\Model\System\Token;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;


use App\Model\Business\Demoment;
use App\Http\Controllers\MessagePacket;


/**
 * 处理试听预约课
 * Class DemomentController
 * @package App\Http\Controllers\Business
 */
class  DemomentController extends BaseController
{
    use MessagePacket;


    /**
     * 获取单一试听预约的信息
     * @param $id
     * @return packetMessage
     */
    function getDemoment($id)
    {
        $id = intval($id);
        $demoment = Demoment::find($id);
        if(empty($demoment)){
            return $this->fail($demoment, '数据不存在');
        }
        return $this->success($demoment);
    }


    /**
     * 批量查询试听预约
     * @param Request $request
     * @return packetMessage
     */
    function getDemoments(Request $request)
    {
        $ttks = Demoment::getAll($request);

        # 需要／不需要 分页
        if($request->has('page')) {
            $data['list'] = $ttks['data'];
            unset($ttks['data']);
            $data['pager'] = $ttks;
        }else{
            $data = $ttks;
        }
        if(empty($data)){
            return $this->fail(false, '数据不存在');
        }
        return $this->success($data);
    }


    /**
     * 添加一个试听预约
     * @param Request $request
     * @return packetMessage
     */
    function  addDemoment(Request $request)
    {
        try {
            $fields = $request->all();
            if (empty($fields)) {
                $this->fail(null, '数据不全');
            }
            # 创建
            $fields['status'] = 0;
            $demoment = new Demoment($fields);
            $demoment->created_by = Token::user()->userid;
            $demoment->updated_by = Token::user()->userid;
            $student = $this->appendStudent($demoment,$request);
            # 附加学生
            $demoment->studentuid = $student->studentuid;

            $demoment->save();
            return $this->success($demoment);

        }catch (\Exception $e) {
            if($demoment instanceof Demoment){
                $demoment->delete();
            }
            return $this->fail(false, '保存失败：'.$e->getMessage());
        }
    }


    /**
     * 更新某个试听预约的信息
     * @param Request $request
     * @return packetMessage
     */
    function  updateDemoment(Request $request, $id=null)
    {
        try{
            $demoment = Demoment::find($id);
            $demoment->update($request->all());
            $demoment->updated_by = Token::user()->userid;

            if($demoment->save()){
                return $this->success($demoment);
            }else{
                return $this->fail(false,'修改失败');
            }
        }catch (\Exception $e){
            return $this->fail(false,'修改失败：'.$e->getMessage());
        }
    }


    /**
     * 删除某个时间
     * @param $id
     * @return packetMessage
     */
    function  deleteDemoment($id)
    {
        try{
            $demoment = Demoment::find($id);
            if($demoment->scheduleid){
                $schedule = Schedule::find($demoment->scheduleid);

                #触发接口事件
                $this->dispatchEvent($schedule, Event::STUDENT, $demoment->studentuid, true);

                # 删除学生，课程关系
                ScheduleStuden::delRelation($demoment->scheduleid, $demoment->studentuid);

                # 更新排课
                $schedule->decrement('usequotas');
                $student = DB::table('schedules_students')->where('scheduleid',$schedule->scheduleid)->first();
                if(is_null($student)){
                    $schedule->unvalide();
                    # 检测是否课程为空
                    if(env('ASYN_MODE')){
                        $this->dispatchEvent($schedule,Event::DELETE);
                    }
                }
                $schedule->save();
            }
            $demoment->delete();
            return $this->success(true,'删除成功');
        }catch (\Exception $e){
            return $this->fail(false, '删除失败:'.$e->getMessage());
        }
    }


    /**
     * 试听课预约
     * @param Request $request
     * @param $id
     * @return packetMessage
     */
    function appintDemoment(Request $request, $id)
    {
        try{
            $demoment = Demoment::find($id);
            $schedule = Schedule::find($request->get('scheduleid'));

            #验证名额是否超出
            if($schedule->quotas <= $schedule->usequotas){
                return $this->fail(false, '预约失败:该课已无可用名额');
            }

            #验证是否重复预约
            $student = ScheduleStuden::where('scheduleid',$request->get('scheduleid'))
                ->where('studentuid',$demoment->studentuid)
                ->first();
            if(!empty($student)){
                return $this->fail(false, '预约失败:当前学生已存在该课下的预约记录');
            }
            $teacher = Teacher::find($schedule->teacheruid);

            #触发接口事件
            $this->dispatchEvent($schedule, Event::STUDENT, $demoment->studentuid);

            # 更新试听
            $demoment->scheduleid = $request->get('scheduleid');
            $demoment->teachername = $teacher->lastname;
            $demoment->begintime = $schedule->begintime;
            $demoment->endtime = $schedule->endtime;
            $demoment->status = 1;
            $demoment->save();
            # 更新排课
            $usequotas = $schedule->usequotas+1;
            $schedule->update(['usequotas' => $usequotas]);
            $schedule->valide();
            $schedule->save();
            # 添加学生，课程关系
            ScheduleStuden::addRelation($demoment->scheduleid, $demoment->studentuid);

            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, '预约失败:'.$e->getMessage());
        }

    }

    /**
     * 取消试听课预约
     * @param Request $request
     * @param $id
     * @return packetMessage
     */
    function unapointDemoment(Request $request, $id)
    {
        try{
            $demoment = Demoment::find($id);
            $schedule = Schedule::find($demoment->scheduleid);

            #触发接口事件
            $this->dispatchEvent($schedule, Event::STUDENT, $demoment->studentuid, true);

            # 更新试听
            $scheduleid = $demoment->scheduleid;
            $demoment->teachername = null;
            $demoment->scheduleid = null;
            $demoment->begintime = null;
            $demoment->endtime = null;
            $demoment->status = 0;
            $demoment->save();

            # 删除学生，课程关系
            ScheduleStuden::delRelation($scheduleid, $demoment->studentuid);
            # 更新排课
            $schedule->decrement('usequotas');
            $student = DB::table('schedules_students')
                ->where('identity',1)
                ->where('scheduleid',$schedule->scheduleid)
                ->first();
            if(is_null($student)){
            $schedule->unvalide();
                # 检测是否课程为空
                if(env('ASYN_MODE')){
                    $this->dispatchEvent($schedule,Event::DELETE);
                }
            }
            $schedule->save();


            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, '取消预约失败:'.$e->getMessage());
        }
    }

    /**
     * 为试听人员，附加学员记录
     */
    private function appendStudent(Demoment $demoment,Request $request)
    {
        try{
            # 排重
            $student = Student::where('ClassInNo', $demoment->ClassInNo)->firstOrFail();
            if($student){
                return $student;
            }
        }catch (\Exception $e){
            $student = New Student();
            $student->name = $demoment->chinesename;
            $student->ClassInNo = $demoment->ClassInNo;
            $password = null;
            if($request->has('password')){
                $password = $request->get('password');
            }
            $this->dispatchStudentEvent($student, Event::CREATE,$password);
            $student->birthday = $demoment->dateofbirth;
            $student->mobile = $demoment->mobile;
            $student->email = $demoment->email;
            $student->save();
            # 关联用户表
            $user = User::where('number',$student->mobile)->first();
            if(empty($user)) {
                $obj = new User();
                $obj->userid = User::generateID();
                $obj->type = User::STUDENT;
                $obj->email = $student->email;
                $obj->number = $student->mobile;
                $obj->islock = User::UNLOCK;
                $password = '123456';
                $config = SystemConfig::find(1);
                if($config){
                    $password = $config->defaultpassword;
                }
                $obj->setSecurityCode($password);
                $obj->updateCreator();
                $student->userid = $obj->userid;
                $obj->save();
            }
            else {
                $student->userid = $user->userid;
            }
            $student->save();
            #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
            $obj = new NoticeConfig([
                'utype'=>2,
                'uid'=>$student->studentuid,
                'ntype'=>1,
                'byemail'=>1,
                'bywechat'=>1,
                'ahead'=>60,
                'perday'=>12]);
            $obj->save();
            $obj2 = new NoticeConfig(['utype'=>2, 'uid'=>$student->studentuid, 'ntype'=>2]);
            $obj2->save();
            return $student;
        }
    }

    /**
     * 抛出事件
     * @param $schedule
     * @param $studentid
     * @param bool $old
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchEvent($schedule,$action, $studentid=null, $old=false)
    {
        try{
            $event = new AppointEvent($schedule, $action);
	        if($studentid){
                $student = Student::find($studentid);
                $event->setIdentity(1);
                $event->setStudent($student, $old);
            }
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }

    /**
     * 学生抛出事件
     * @param Student $student
     * @param $action
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchStudentEvent(Student $student, $action,$password = null)
    {
        try{
            $event = new StudentEvent($student, $action,$password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }


}